package com.dragon.aipictures.test2;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

@Slf4j
@Component
public class TableSplitter {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ShardMetadataService metadataService;
    @Autowired
    private DataMigratorFactory migratorFactory;
    
    @Async("splitTaskExecutor")
    public void splitTable(Long spaceId) {
        try {
            // 1. 状态标记
            metadataService.updateStatus(spaceId, "MIGRATING");
            
            // 2. 创建分表
            createNewTables(spaceId);
            
            // 3. 数据迁移
            DataMigrator migrator = migratorFactory.createMigrator(spaceId);
            migrator.migrate();
            
            // 4. 更新元数据
            updateMetadata(spaceId, 4);
            
            // 5. 清理旧表（延迟执行）
            scheduleTableCleanup(spaceId);
        } catch (Exception e) {
            handleSplitFailure(spaceId, e);
        }
    }

    private void createNewTables(Long spaceId) {
        IntStream.range(0, 4).forEach(i -> {
            String ddl = "CREATE TABLE IF NOT EXISTS picture_" + spaceId + "_" + i 
                       + " (id BIGINT PRIMARY KEY, "
                       + "space_id BIGINT NOT NULL, "
                       + "content BLOB, "
                       + "created_at DATETIME)";
            jdbcTemplate.execute(ddl);
        });
    }

    private void updateMetadata(Long spaceId, int tableCount) {
        jdbcTemplate.update(
            "UPDATE sharding_metadata SET table_count = ?, version = version + 1, status = 'ACTIVE' "
            + "WHERE space_id = ?",
            tableCount, spaceId
        );
    }

    private void scheduleTableCleanup(Long spaceId) {
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.schedule(() -> {
            jdbcTemplate.execute("DROP TABLE IF EXISTS picture_" + spaceId);
        }, 24, TimeUnit.HOURS); // 延迟24小时删除旧表
    }

    private void handleSplitFailure(Long spaceId, Exception e) {
        log.error("分表失败 spaceId: {}", spaceId, e);
        jdbcTemplate.update("DELETE FROM sharding_metadata WHERE space_id = ?", spaceId);
        IntStream.range(0, 4).forEach(i -> {
            jdbcTemplate.execute("DROP TABLE IF EXISTS picture_" + spaceId + "_" + i);
        });
    }
}